<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Order;
use App\Supports\Delivery\Express;
use App\Http\Controllers\Api\V1\Queries\OrderQuery;
use App\Services\MakeProductOrder\MakeProductOrder;
use App\Http\Controllers\Api\V1\Resources\OrderResource;
use App\Services\ReceiveProductOrder\ReceiveProductOrder;
use App\Services\MakeProductOrder\MakeProductOrderRequest;
use App\Services\ReceiveProductOrder\ReceiveProductOrderRequest;
use App\Services\CloseUnpaidProductOrder\CloseUnpaidProductOrder;
use App\Services\CloseUnpaidProductOrder\CloseUnpaidProductOrderRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class OrdersController extends Controller
{
	public function index(OrderQuery $query): AnonymousResourceCollection
	{
		$user = request()->user();
		$condition = request('condition');
		$query = $query->where('user_id', $user->id);
		$orders = $query->inquire($condition)->orderByDesc('id')->paginate();
		return OrderResource::collection($orders);
	}

	public function show($id): OrderResource
	{
		$order = app(OrderQuery::class)->findOrFail($id);
		return new OrderResource($order);
	}

	public function count(): JsonResponse
	{
		$count = Order::inquire()->count();
		return response()->json(['count' => $count]);
	}

	public function counts(): JsonResponse
	{
		$counts = request()->user()->ordersCount();
		return response()->json(['counts' => $counts]);
	}

    public function store(MakeProductOrderRequest $request): OrderResource
    {
    	$order = app(MakeProductOrder::class, [
		    'user' => $request->user(),
		    'address' => $request->getAddress(),
		    'items' => $request->items(),
	    ])->make();

	    return new OrderResource($order);
    }

    public function express(Order $order): JsonResponse
    {
    	$result = app(Express::class)->track($order);

    	if(isset($result['returnCode']) && $result['returnCode'] == 500){
    		$result = [
				'message'=>'ok',
				"data" =>[
					[
					"time"=>(string)$order->created_at,
					"ftime"=>(string)$order->created_at,
					"context"=> "正在出库中..."
					]
				]
			];
    	}
    	return response()->json(['data' => $result]);
    }

    public function receive(ReceiveProductOrderRequest $request, Order $order)
    {
	    $this->authorize('own', $order);
	    app(ReceiveProductOrder::class, ['order' => $order])->receive();
	    return response(null, 204);
    }

    public function destroy(Order $order)
    {
    	$this->authorize('own', $order);
    	$order->delete();
	    return response(null, 204);
    }
}
